package com.auto.learning.service;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.auto.learning.R;
import com.auto.learning.activity.PlayListActivity;
import com.auto.learning.bean.AnchorBean;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.DownLoadBean;
import com.auto.learning.bean.ReadModeBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.ProgressEvent;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.Cache;
import com.auto.learning.net.DownLoadInfo;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FileUtil;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;

public class DownLoadManager{
	
	private final static int GETCACHEDATA_SUCCESS = 1;
	private final static int GETANCHOR_SUCCESS = 100;
	private Context context;
	
	private PrepareDownLoadThread downLoadThread;
	
	private ArrayList<Integer> downloadTask = new ArrayList<Integer>();
//	private ArrayList<Integer> temp_download_all_list = new ArrayList<Integer>();

	private Handle handler =new Handle(context){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result = (ResponeResult)msg.obj;
				ReadModeBean readModeBean = new Gson().fromJson(result.getData(), new TypeToken<ReadModeBean>(){}.getType());
				Cache.cacheReadMode2Local(readModeBean);
				getLocalBookBean(readModeBean.getBookId());
				break;
			case GETCACHEDATA_SUCCESS:  //发送下载，取出要下载的链接和总的大小
				BookBean bookBean = (BookBean) msg.obj;
				if (bookBean == null) {
					break;
				}
				ImageView imageView = new ImageView(context);
				ImageLoader.getInstance().displayImage(bookBean.getFaceImgPlay(), imageView);
				DownLoadBean downLoadBean = new DownLoadBean();
				int hasDownLoad = 0 ;
				ArrayList<String> urlList = new ArrayList<String>(); 
				List<SelectionVo> selectionVos = bookBean.getSectionList();
				if (selectionVos != null && selectionVos.size() > 0) {
					for (SelectionVo selectionVo : selectionVos) {
						if (bookBean.getProSize() > 0) {
							if (checkDownLoadStatus(selectionVo.getProAudioUrl(), selectionVo.getProSize(),selectionVo.getBookId())) {
								urlList.add(selectionVo.getProAudioUrl());
							} else {
								hasDownLoad += selectionVo.getProSize();
							}
						}
						if (bookBean.getDoubiSize() > 0) {
							if (checkDownLoadStatus(selectionVo.getDoubiAudioUrl(), selectionVo.getDoubiSize(),selectionVo.getBookId())) {
								urlList.add(selectionVo.getDoubiAudioUrl());
							} else {
								hasDownLoad += selectionVo.getDoubiSize();
							}
						}
						if (bookBean.getEnSize() > 0) {
							if (checkDownLoadStatus(selectionVo.getEnAudioUrl(), selectionVo.getEnSize(),selectionVo.getBookId())) {
								urlList.add(selectionVo.getEnAudioUrl());
							} else {
								hasDownLoad += selectionVo.getEnSize();
							}
						}
					}
				}
				Log.d("urlList",bookBean.getBookId() +"----"+ urlList.size()+"");
				if (urlList != null && urlList.size() > 0) {
					downLoadBean.setHasDownLoadSize(hasDownLoad);
					downLoadBean.setBookId(bookBean != null ? bookBean.getBookId() : 0);
					downLoadBean.setTotalSize(bookBean != null ? bookBean.getProSize() + bookBean.getDoubiSize() + bookBean.getEnSize() : 0);
					downLoadBean.setUrlList(urlList);
					EventBus.getEventBus("list_download").post(downLoadBean);
					ProgressEvent event = new ProgressEvent();
					event.setCurrentRatio(0);
					event.setBookId(bookBean != null ? bookBean.getBookId() : 0);
					EventBus.getEventBus("downloadProgress").post(event);
				}else {
					if (TemporaryVariable.temp_download_all_list != null && TemporaryVariable.temp_download_all_list.contains(bookBean.getBookId())) {
						TemporaryVariable.temp_download_all_list.remove(TemporaryVariable.temp_download_all_list.indexOf(bookBean.getBookId()));
					}
				}
				break;
			case GETANCHOR_SUCCESS:
				try {
					List<AnchorBean> list = (List<AnchorBean>) msg.obj;
					if (list != null  && list.size() > 0) {
						for (AnchorBean anchorBean : list) {
							ImageView view = new ImageView(context);
							ImageLoader.getInstance().displayImage(anchorBean.getFace(), view);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		};
	};
	
	
	public DownLoadManager(Context context){
		this.context = context;
		downLoadThread = new PrepareDownLoadThread();
		downLoadThread.start();
	}
	
	private static DownLoadManager downLoadManager;
	
	public static DownLoadManager getInstance(Context context){
		if (downLoadManager == null) {
			downLoadManager = new DownLoadManager(context);
		}
		return downLoadManager;
	}
	
	public DownLoadManager setContext(Context context){
		this.context = context;
		return this;
	}
	
	/**
	 * 添加要下載的ID
	 */
	public void addDownLoadId(int _bookId){
		if (downloadTask != null && !downloadTask.contains(_bookId) && !TemporaryVariable.temp_download_all_list.contains(_bookId) && !TemporaryVariable.downLoadedList.contains(_bookId)) {
			downloadTask.add(_bookId);
			if (TemporaryVariable.temp_download_all_list != null && !TemporaryVariable.temp_download_all_list.contains(_bookId)) {
				TemporaryVariable.temp_download_all_list.add(_bookId);
			}
			if (downLoadThread != null) {
				synchronized (downLoadThread) {
					downLoadThread.notify();
				}
			}
		}
	}
	
	/**
	 * 批量下载
	 */
	public void addDownLoadIds(ArrayList<Integer> mBookIds){
		if (mBookIds!= null && mBookIds.size() > 0) {
			for (Integer element : mBookIds) {
				if (downloadTask != null && !downloadTask.contains(element) && !TemporaryVariable.temp_download_all_list.contains(element) && !TemporaryVariable.downLoadedList.contains(element)) {
					downloadTask.add(element);
					if (TemporaryVariable.temp_download_all_list != null && !TemporaryVariable.temp_download_all_list.contains(element)) {
						TemporaryVariable.temp_download_all_list.add(element);
					}
				}
			}
		}
		if (downLoadThread != null) {
			synchronized (downLoadThread) {
				downLoadThread.notify();
			}
		}
	}
	
	/**
	 * 下載等待時清空
	 */
	public void clearAllDownLoadList(){
		if (TemporaryVariable.temp_download_all_list != null) {
			TemporaryVariable.temp_download_all_list.clear();
		}
	}
	
	/**
	 * 检查本地是否下载
	 * @param url
	 * @param urlLength
	 */
	public boolean checkDownLoadStatus(String url, int urlLength,int bookId){
		boolean flag = true;
		if (!TextUtils.isEmpty(url)) {
			String fileName = CommonMethod.getFileName(url);
			File file = new File(FileUtil.getFileCachePath() + DownLoadInfo.DOWNLOAD +"/" + bookId +"/" + fileName);
			if (file.exists()) {
				if (file.length() == urlLength) {
					flag = false;
				} else {
					file.delete();
				}
			}
		}
		return flag;
	}

	
	private void getLocalBookBean(final int bookId){
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					BookBean bookBean = StaticReference.mutilDBSupport.getDao(BookBean.class).queryForId(bookId);
					List<SelectionVo> selectionVos = StaticReference.mutilDBSupport.getDao(SelectionVo.class).queryForEq("bookId", bookId);
					if (bookBean != null && selectionVos != null ) {
						bookBean.setSectionList(selectionVos);	
					}
					handler.obtainMessage(GETCACHEDATA_SUCCESS,bookBean).sendToTarget();
				} catch (SQLException e) {
					e.printStackTrace();
				}				
			}
		});
	}
	
	boolean isEmpty(String txt){
		return TextUtils.isEmpty(txt);
	}
	
	public void showDialog(final int _bookId,int needDownloadSize){
		CommonAlertDialog alertDialog = new CommonAlertDialog(context);
		if (needDownloadSize > 0) {
			alertDialog.setTextMessage(String.format(context.getResources().getString(R.string.download_notice), CommonMethod.calculationNum(needDownloadSize)));
		}else {
			alertDialog.setTextMessage(context.getResources().getString(R.string.net_ismobile_connect_download));
		}
		alertDialog.setShowTitle(true);
		String[] a = {context.getResources().getString(R.string.app_continue),context.getResources().getString(R.string.app_cancel)};
		alertDialog.setBtns(new DialogListener() {
			
			@Override
			public void okButtonClick(Dialog dialog) {
				dialog.dismiss();
				
				addDownLoadId(_bookId);
				CommonMethod.makeNotice(context, "已加入下载列表");
			}

			@Override
			public void cancelButtonClick(Dialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void otherButtonClick(Dialog dialog) {
				dialog.dismiss();
			}
		},a);
		alertDialog.show();
	}
	
	/**
	 * 一个下载项目
	 * @param needDownloadSize
	 */
	public void prepareBefore(int _bookId, int needDownloadSize){
		if (!(boolean)SharedPreferencesUtils.getParam(context, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
			switch (CommonMethod.getNetworkState(context)) {
			case 0:
				CommonMethod.makeNotice(context, context.getResources().getString(R.string.connect_err_io));
				break;
			case 1:
				
				addDownLoadId(_bookId);
				CommonMethod.makeNotice(context, "已加入下载列表");
				break;
			case 2:
				showDialog(_bookId,needDownloadSize);
				break;
			}
		}else {
			addDownLoadId(_bookId);
			CommonMethod.makeNotice(context, "已加入下载列表");
		}
	}
	
	
	/**
	 * 下载之前的准备数据,确定下载完成后要保存的数据，先读取本地，要是本地没有，则从网络获取数据
	 * @author wangjianjun
	 */
	class PrepareDownLoadThread extends Thread {

		@Override
		public void run() {
			while (true) {
				while (downloadTask != null && downloadTask.size() > 0) {
					int downloadId = downloadTask.remove(0);
					ResponeResult responeResult = null;
					if (downloadId != 0 && HttpRequestHelper.getAnchorList(context, downloadId, handler)) {
						try {
							BookBean bookBean = StaticReference.mutilDBSupport.getDao(BookBean.class).queryForId(downloadId);
							if (bookBean == null || (bookBean != null && checkDataComplete(bookBean))) {
								// 请求
								List<NameValuePair> params = new ArrayList<NameValuePair>();
								params.add(new BasicNameValuePair(HttpRequestHelper.USERID,String.valueOf(SharedPreferencesUtils.getParam(context,HttpRequestHelper.USERID, 0))));
								params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(downloadId)));
								HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.READ_MODE, params,context);
								String _result = HttpHelper.entity2String(entity);
								JSONObject jsonResult = new JSONObject(_result);
								JSONObject result = jsonResult.getJSONObject(HttpCommonInfo.RESULT);
								int code = result.getInt(HttpCommonInfo.RESULT_CODE);
								String msg = result.getString(HttpCommonInfo.RESULT_MSG);
								responeResult = new ResponeResult();
								responeResult.setCode(code);
								responeResult.setMsg(msg);
								if (code == 0) {
									responeResult.setData(jsonResult.getString(HttpCommonInfo.DATA));
									handler.obtainMessage(HttpRequestHelper.GETDATA_SUCCESS,responeResult).sendToTarget();
								} else {
									handler.sendEmptyMessage(-100);
								}
							} else {
								try {
									List<SelectionVo> selectionVos = StaticReference.mutilDBSupport.getDao(SelectionVo.class).queryForEq("bookId", downloadId);
									bookBean.setSectionList(selectionVos);
									handler.obtainMessage(GETCACHEDATA_SUCCESS,bookBean).sendToTarget();
								} catch (SQLException e) {
									e.printStackTrace();
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
							if (TemporaryVariable.temp_download_all_list != null && TemporaryVariable.temp_download_all_list.contains(downloadId)) {
								TemporaryVariable.temp_download_all_list.remove(TemporaryVariable.temp_download_all_list.indexOf(downloadId));
							}
						}
					}
				}
				synchronized (this) {
					try {
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	private boolean checkDataComplete(BookBean bookBean){
		if (isEmpty(bookBean.getAbout())) {
			return true;
		}
		if (isEmpty(bookBean.getGoldWord())) {
			return true;
		}
		if (isEmpty(bookBean.getNationImg())) {
			return true;
		}
		if (isEmpty(bookBean.getCommentNum())) {
			return true;
		}
		if (isEmpty(bookBean.getListenNum())) {
			return true;
		}
		if (isEmpty(bookBean.getFaceImg())) {
			return true;
		}
		if (isEmpty(bookBean.getSlogan())) {
			return true;
		}
		return false;
	}
}
	

